/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.groovy

import cool.taomu.utils.FileUtils
import groovy.lang.GroovyClassLoader
import groovy.lang.GroovyClassLoader.InnerLoader
import groovy.lang.GroovyCodeSource
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import java.nio.charset.Charset
import org.apache.commons.io.IOUtils
import org.codehaus.groovy.runtime.IOGroovyMethods
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

class GroovyScript extends ClassLoader implements AutoCloseable {
	val static LOG = LoggerFactory.getLogger(GroovyScript)
	var InnerLoader il = null;

	new() {
	}

	new(String path) throws Exception{
		this(path, Thread.currentThread.contextClassLoader)
	}

	new(String path, ClassLoader loader) throws Exception{
		LOG.info(String.format("加载脚本:%s", path))
		var scripts = FileUtils.scanningFile(new File(path));
		var scriptStr = scripts.filterNull.map [
			return org.apache.commons.io.FileUtils.readFileToString(new File(it), "UTF-8")
		].join("\n");
		this.loaderScript(scriptStr, loader);
	}

	def void loaderScript(String coding, ClassLoader loader) {
		try(var input = IOUtils.toInputStream(coding,Charset.forName("UTF-8"))) {
			var gl = new GroovyClassLoader(loader === null ? Thread.currentThread.contextClassLoader : loader);
			il = new InnerLoader(gl);
			var scriptText = IOGroovyMethods.getText(input);
			var c = new GroovyCodeSource(scriptText, "./", "/groovy/script");
			il.parseClass(c);
		}catch(Exception ex){
			throw new Exception(ex);
		}
	}

	override findClass(String name) {
		return il.loadClass(name);
	}

	override close() throws Exception {
		LOG.debug("Groovy class loader close");
		if (il !== null) {
			il.close();
		}
	}
}
